package com.zmc.lostfound.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import org.apache.http.HttpStatus;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zmc
 * @description 统一返回结果集
 */
public class Result extends HashMap<String, Object> implements Serializable {

    private static final long serialVersionUID = 1L;

    public Result() {
        this.put("code", HttpStatus.SC_OK);
        this.put("message", "success");
    }

    public static Result error() {
        return Result.error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
    }

    public static Result error(String message) {
        return Result.error(HttpStatus.SC_INTERNAL_SERVER_ERROR, message);
    }

    public static Result error(int code, String message) {
        Result result = new Result();
        result.put("code", code);
        result.put("message", message);
        return result;
    }

    public static Result ok() {
        return new Result();
    }

    public static Result ok(String message) {
        Result result = new Result();
        result.put("message", message);
        return result;
    }

    public static Result ok(Map<String, Object> map) {
        Result result = new Result();
        result.putAll(map);
        return result;
    }

    @Override
    public Result put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    @Override
    public Object get(Object key) {
        return super.get(key);
    }

    public Integer getCode() {
        return Integer.valueOf(this.get("code").toString());
    }

    public String getMessage() {
        return this.get("message").toString();
    }

    public <T> T getBean(String key, Class<T> type) {
        Object object = this.get(key);
        if (this.getCode().equals(HttpStatus.SC_OK) && object != null) {
            return JSONUtil.toBean(JSONUtil.toJsonStr(object), type);
        }
        return null;
    }

    public <T> List<T> getBeanList(String key, Class<T> type) {
        Object object = this.get(key);
        if (this.getCode().equals(HttpStatus.SC_OK) && object != null) {
            return JSONUtil.toList(JSONUtil.toJsonStr(object), type);
        }
        return null;
    }

    public Map<String, Object> getBeanMap(String key) {
        Object object = this.get(key);
        if (this.getCode().equals(HttpStatus.SC_OK) && object != null) {
            return BeanUtil.beanToMap(
                    object, new HashMap<>(20),
                    CopyOptions.create()
                            .setIgnoreNullValue(true)
                            .setFieldValueEditor((fieldName, fieldValue) -> fieldValue == null ? null : fieldValue.toString())
            );
        }
        return null;
    }

}
